package com.goodmr.passport.webapp.config;

import com.goodmr.passport.webapp.resolver.UserIdResolver;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * 应用 MVC 配置
 *
 * @author <a href="mailto:bingdong13@msn.com">bigo</a>
 */
@Configuration
@Slf4j
public class RestServiceConfig implements WebMvcConfigurer {

    private final UserIdResolver userIdResolver;

    @Autowired
    public RestServiceConfig(UserIdResolver userIdResolver) {
        log.info("Initializing RestService ");

        this.userIdResolver = userIdResolver;
    }

    /**
     * 设置跨域访问
     *
     * @param registry 注册
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {

        String[] allowedHeaders = new String[]{
                "Content-Type", "Access-Control-Allow-Headers",
                "Authorization", "X-Client-Language", "X-Client-Ip",
                "X-Client-Id", "X-Client-Sign", "X-Client-Timestamp"
        };

        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD")
                .allowedHeaders(allowedHeaders)
                .allowCredentials(true)
                .maxAge(31536000);
    }

    /**
     * 消息json格式转换
     *
     * @param converters 转换器
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        GsonHttpMessageConverter msgConverter = new GsonHttpMessageConverter();
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        msgConverter.setGson(gson);
        converters.add(msgConverter);
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(userIdResolver);
    }
}
